package com.example.redstarcommerce.cn.dh.user.service.impl;

import com.example.redstarcommerce.cn.dh.common.vo.Result;
import com.example.redstarcommerce.cn.dh.user.pojo.User;
import com.example.redstarcommerce.cn.dh.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.*;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Result<List<User>> result = userService.getByName(username, null);
        if (    !result.getData().isEmpty()) {
            User user = result.getData().get(0);
            return new User(user.getName(), user.getPassword(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
        } else {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
    }
}
